// 引入Sequelize模块
const Sequelize = require('sequelize');

// 引入数据库实例
const db = require('../db');
const user = require('./user');
const artClass = require('./artClass');
const path = require('path');
const tokenHelper = require(path.resolve(__dirname, '../common/tokenHelper'));

const artPPT = db.define("artPPT", {
    // 主键
    objectId: {
        type: Sequelize.STRING(20),
        allowNull: false,
        unique: true,
        primaryKey: true
    },

    userId: {
        type: Sequelize.STRING(20),
        comment: "创建人"
    },

    number: {
        type: Sequelize.STRING(20),
        comment: "编号"
    },

    courceNumber: {
        type: Sequelize.STRING(10),
        comment: "编号"
    },

    price: {
        type: Sequelize.INTEGER,
        comment: "价格",
        get() {
            // 获取原始价格
            let price = this.getDataValue('price') || 0;

            // 从配置中获取价格模式
            // '0' = 全部免费（返回0）
            // '1' = 显示原价（返回真实价格）
            const priceMode = tokenHelper.getCoursePriceModeSync();

            if (priceMode === '1') {
                // 显示原价模式
                return price;
            } else {
                // 免费模式（默认）
                return 0;
            }
        }
    },

    size: {
        type: Sequelize.STRING(20),
        comment: "文件大小",
        defaultValue: 0
    },

    title: {
        type: Sequelize.STRING,
        comment: "标题"
    },

    desc: {
        type: Sequelize.TEXT,
        comment: "描述"
    },

    age: {
        type: Sequelize.VIRTUAL,
        comment: "年龄",
        get() {
            let ageMin = this.getDataValue('ageMin');
            let ageMax = this.getDataValue('ageMax');
            let age = this.getDataValue('age') || "通用";
            let returnAge
            if (ageMin) {
                returnAge = ageMin + "~"
                if (ageMax && ageMax != 99) returnAge += ageMax
                returnAge += "岁"
            } else {
                returnAge = age
            }
            return returnAge
        }
    },

    ageMin: {
        type: Sequelize.INTEGER,
        comment: "年龄最小值",
        defaultValue: 3
    },

    ageMax: {
        type: Sequelize.INTEGER,
        comment: "年龄最大值",
        defaultValue: 99
    },

    page: {
        type: Sequelize.INTEGER,
        comment: "页数，用来获取封面图",
        defaultValue: 10,
    },

    content: {
        type: Sequelize.TEXT,
        comment: "内容"
    },

    downLoadNum: {
        type: Sequelize.INTEGER,
        defaultValue: 0,
        comment: "下载次数",
        get() {
            let downLoadNum = this.getDataValue('downLoadNum');
            if (downLoadNum) {
                return downLoadNum
            } else {
                return Math.floor(Math.random() * 200) + 1
            }
        }
    },

    classDesc: {
        type: Sequelize.TEXT,
        comment: "教程分类"
    },

    tags: {
        type: Sequelize.JSON,
        defaultValue: [],
        comment: "标签",
    },

    type: {
        type: Sequelize.VIRTUAL,
        defaultValue: "单个",
        comment: "类型",
        get() {
            //let fileType = this.getDataValue('fileType');
            let fileUrls = this.getDataValue('fileUrls') || []
            if (fileUrls.length > 1) {
                return "合集"
            } else {
                return "单个"
            }
        }
    },

    images: {
        type: Sequelize.JSON,
        defaultValue: [],
        comment: "封面图",
        get() {
            let newImages = []
            let courceNumber = this.getDataValue('courceNumber');
            if (courceNumber) {
                let title = this.getDataValue('title') || [];

                newImages.push("https://qiniu.jimuzhou.cloud/newFiles/" + courceNumber + "/" + title + "/s.png")
            } else {
                let longImages = this.getDataValue('images') || [];

                for (let thisImage of longImages) {
                    if (thisImage.indexOf("imageMogr2/format/WebP") == -1) thisImage = thisImage + "?imageMogr2/format/WebP"
                    if (thisImage.includes("http://qiniu.jimuzhou.cloud")) thisImage = "https://qiniu.jimuzhou.cloud" + thisImage.split("http://qiniu.jimuzhou.cloud")[1]

                    newImages.push(thisImage)
                }
            }

            return newImages
        },
        set(longImages) {
            let newImages = []
            for (let thisImage of longImages) {
                if (thisImage.indexOf("imageMogr2/format/WebP") == -1) {
                    thisImage = thisImage.split("?imageMogr2/format/WebP")[0]
                }
                newImages.push(thisImage)
            }
            this.setDataValue("images", newImages)
        }
    },

    courseId: {
        type: Sequelize.STRING(20),
        allowNull: true,
        comment: "关联课程ID（外键）",
    },

    getType: {
        type: Sequelize.JSON,
        defaultValue: ["付费"],
        comment: "获取方式",
    },

    videoUrl: {
        type: Sequelize.STRING,
        defaultValue: '',
        comment: "视频链接简介"
    },

    sourceFrom: {
        type: Sequelize.STRING(20),
        defaultValue: '',
        comment: "课件来源"
    },

    baiduDeskLink: {
        type: Sequelize.STRING,
        defaultValue: '',
        comment: "百度网盘链接"
    },

    baiduDeskImage: {
        type: Sequelize.STRING,
        defaultValue: '',
        comment: "百度网盘小程序下载图",
        get() {
            const baiduDeskLink = this.getDataValue('baiduDeskLink');
            let baiduDeskImage = this.getDataValue('baiduDeskImage') || '';
            if (baiduDeskImage) baiduDeskImage = baiduDeskImage + "?imageMogr2/format/WebP"
            else if (baiduDeskLink) {
                let thisWords = baiduDeskLink.split("https://pan.baidu.com/s/")
                let shortUrl = thisWords[1].replace("?", "&")
                baiduDeskImage = "https://pan.baidu.com/api/wechat/qrcode?width=150&clienttype=0&shorturl=" + shortUrl
            }
            return baiduDeskImage
        },
        set(value) {
            if (value) this.setDataValue("baiduDeskImage", value.split("?imageMogr2/format/WebP")[0])
        },
    },

    longImages: {
        type: Sequelize.JSON,
        defaultValue: [],
        comment: "课件详情图",
        get() {

            let newImages = []
            let courceNumber = this.getDataValue('courceNumber');
            if (courceNumber) {

                let title = this.getDataValue('title') || [];
                newImages.push("https://qiniu.jimuzhou.cloud/newFiles/" + courceNumber + "/" + title + "/l01.png")
                newImages.push("https://qiniu.jimuzhou.cloud/newFiles/" + courceNumber + "/" + title + "/l02.png")
            } else {
                let longImages = this.getDataValue('longImages') || [];
                for (let thisImage of longImages) {
                    if (thisImage.includes("http://qiniu.jimuzhou.cloud")) {
                        thisImage = "https://qiniu.jimuzhou.cloud" + thisImage.split("http://qiniu.jimuzhou.cloud")[1]
                    }
                    /*if (thisImage.indexOf("/sf") == -1) {
                        thisImage = thisImage + "/sf"
                    }*/
                    newImages.push(thisImage)
                }
            }
            return newImages
        },
        set(longImages) {
            let newImages = []
            for (let thisImage of longImages) {
                if (thisImage.indexOf("imageMogr2/format/WebP") == -1) {
                    thisImage = thisImage.split("?imageMogr2/format/WebP")[0]
                }
                newImages.push(thisImage)
            }
            this.setDataValue("longImages", newImages)
        }
    },

    dominantColor: {
        type: Sequelize.STRING(7),
        comment: "主色调1",
        defaultValue: null,
        allowNull: true
    },

    dominantColor2: {
        type: Sequelize.STRING(7),
        comment: "主色调2",
        defaultValue: null,
        allowNull: true
    },

    isNice: {
        type: Sequelize.BOOLEAN,
        defaultValue: false,
        comment: "是否是精选内容"
    },

    isNew: {
        type: Sequelize.BOOLEAN,
        defaultValue: true,
        comment: "是否是新版",
        get() {
            const baiduDeskLink = this.getDataValue('baiduDeskLink');
            const isNew = this.getDataValue('isNew');
            if (baiduDeskLink) {
                return true
            } else {
                return false
            }
        }
    },

    isBaiduFile: {
        type: Sequelize.BOOLEAN,
        defaultValue: false,
        comment: "是否是网盘同步文件",
    },


    path: {
        type: Sequelize.STRING(),
        defaultValue: '',
        comment: "百度网盘路径"
    },

    fs_id: {
        type: Sequelize.VIRTUAL,
        comment: "是否是网盘同步文件",
        get() {
            const isBaiduFile = this.getDataValue('isBaiduFile');
            const number = this.getDataValue('number');
            if (isBaiduFile) {
                return number
            } else {
                return ""
            }
        }
    },

    status: {
        type: Sequelize.INTEGER,
        defaultValue: 1,
        comment: "是否已审核，1表示已审核，0表示未审核,-1表示未通过",
    },

    adNum: {
        type: Sequelize.INTEGER,
        defaultValue: 1,
        comment: "需要观看的广告数量",
        get() {
            const fileType = this.getDataValue('fileType');
            const adNum = this.getDataValue('adNum');
            //if (adNum) return adNum
            if (fileType == "课件") {
                return 1
            } else if (fileType == '课程') {
                return 5
            } else {
                return 1
            }
        }
    },

    statusDesc: {
        type: Sequelize.VIRTUAL,
        get() {
            const status = this.getDataValue('status');
            if (status == 1) {
                return "已审核"
            } else if (status == 0) {
                return "未审核"
            }
        }
    },

    fileUrls: {
        type: Sequelize.JSON,
        defaultValue: '',
        comment: "文件链接",
        get() {
            const fileUrls = this.getDataValue('fileUrls');
            for (let fileUrl of fileUrls) {
                if (fileUrl.fileUrl.indexOf("https://file.jimuzhou.cloud/") != -1) {
                    let thisValues = fileUrl.fileUrl.split("https://file.jimuzhou.cloud/")
                    fileUrl.fileUrl = "https://artppt-1306121076.cos.ap-nanjing.myqcloud.com/" + thisValues[1]
                }
            }
            return fileUrls
        }
    },

    fileType: {
        type: Sequelize.STRING(20),
        comment: "资源类型",
        defaultValue: '课件',
        get() {
            const fileType = this.getDataValue('fileType');
            if (fileType) {
                return fileType
            } else {
                return "课件"
            }
        }
    },

    TypeId: {
        type: Sequelize.STRING(20),
        comment: "关联专题"
    },

    ClassId: {
        type: Sequelize.STRING(20),
        comment: "关联教程分类"
    },

    createdAt: {
        type: Sequelize.DATE,
        get() {
            const rawValue = this.getDataValue('createdAt');
            return dateFormat(rawValue, 'yyyy-mm-dd HH:MM:ss');
        }
    },

    updatedAt: {
        type: Sequelize.DATE,
        get() {
            const rawValue = this.getDataValue('updatedAt');
            return dateFormat(rawValue, 'yyyy-mm-dd HH:MM:ss');
        }
    },
}, {
    underscored: false,
    tableName: "artPPT",
});

artPPT.belongsTo(user.user, {
    foreignKey: 'userId',
    as: "user"
});

artClass.artType.hasMany(artPPT, {
    foreignKey: 'TypeId',
    as: "typeList",
})
artPPT.belongsTo(artClass.artType, {
    foreignKey: 'TypeId',
    as: "typeDesc",
    onDelete: 'SET NULL',
    onUpdate: 'SET NULL',
});

artPPT.belongsTo(artClass.artClass, {
    foreignKey: 'ClassId',
    as: "class",
    onDelete: 'SET NULL',
    onUpdate: 'SET NULL',
});

// 自关联：课程 hasMany 课件
artPPT.hasMany(artPPT, {
    foreignKey: 'courseId',
    as: 'coursewares',
    constraints: false, // 不创建外键约束，因为是自关联
});

// 自关联：课件 belongsTo 课程
artPPT.belongsTo(artPPT, {
    foreignKey: 'courseId',
    as: 'course',
    constraints: false,
});

/*(async () => {
    artPPT.sync({
        alter: true
    });

    console.log("资源同步成功")
})();*/



module.exports = artPPT;
